<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :title="title"
    width="1200px"
  >
    <el-alert
      :closable="false"
      :style="{marginBottom: '20px'}"
      show-icon
      title="提示: 客户代码、产品型号、工艺规范编号、工序号和封装形式至少填写一个"
      type="info"/>
    <!-- <dynForm
      ref="dataForm"
      :form-disable="formDisable"
      :info-form="infoForm"
      :search-tags="searchTags"
      :select-list="selectList"
    /> -->
    <el-form
      ref="dataForm"
      :inline="true"
      :disabled="formDisable"
      :model="infoForm"
      label-width="120px">
      <el-form-item :label="this.$t('customer')">
        <el-input v-model="infoForm.customer" :placeholder="`${$t('pleaseInput')}${$t('customer')}`" clearable/>
      </el-form-item>
      <el-form-item :label="this.$t('productName')">
        <el-input v-model="infoForm.productName" :placeholder="`${$t('pleaseInput')}${$t('productName')}`" clearable/>
      </el-form-item>
      <el-form-item :label="this.$t('processSpecificationNumber')">
        <el-input v-model="infoForm.processSpecificationNo" :placeholder="`${$t('pleaseInput')}${$t('processSpecificationNumber')}`" clearable/>
      </el-form-item>
      <el-form-item :label="this.$t('processNo')">
        <el-input v-model="infoForm.processFlow" :placeholder="`${$t('pleaseInput')}${$t('processNo')}`" clearable/>
      </el-form-item>
      <el-form-item :label="this.$t('packageType')">
        <el-select
          v-model="infoForm.packaingFormsCode"
          :placeholder="`${$t('pleaseSelect')}${$t('packageType')}`"
          clearable
          filterable
          allow-create
          default-first-option
          @change="addpackageTypeList"
        >
          <el-option
            v-for="item in packaingCodeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="opt-btns">
      <el-button
        :disabled="tableDisable"
        type="success"
        @click="handleAddCol"
      >{{ $t("add") }}</el-button
      >
    </div>
    <div class="table-box">
      <dynTable
        ref="dynTable"
        :loading="false"
        :table-data="tableData"
        :table-columns="tableColumns"
      />
    </div>
    <span v-show="!tableDisable" slot="footer">
      <el-button icon="el-icon-circle-close" @click="handleClose">{{
        $t("cancel")
      }}</el-button>
      <el-button
        v-btnThrottle="doSave"
        type="primary"
        icon="el-icon-receiving"
      >{{ $t("save") }}</el-button
      >
  </span></el-dialog
  >
</template>

<script>
import {
  doAdd,
  doUpdate,
  getInfos,
  getPackageTypeList
} from '@/api/auto-analyze-warning/SBLIndexSetting'
export default {
  name: 'SBLSettingDialog',
  data() {
    return {
      dialogVisible: false,
      title: '',
      infoForm: {},
      formDisable: false,
      tableDisable: false,
      selectList: {},
      searchTags: [

        { label: this.$t('customer'), prop: 'customer', tag: 'DynInput' },
        { label: this.$t('productName'), prop: 'productName', tag: 'DynInput' },
        {
          label: this.$t('processSpecificationNumber'),
          prop: 'processSpecificationNo',
          tag: 'DynInput'
        },
        { label: this.$t('processNo'), prop: 'processFlow', tag: 'DynInput' },
        {
          label: this.$t('packageType'),
          prop: 'packaingFormsCode',
          tag: 'DynSelect'
        }
      ],
      packaingCodeList: [],
      // rules: {
      //   customer: [{ required: true, message: `${this.$t('pleaseInput')}${this.$t('customer')}`, trigger: 'blur' }],
      //   productName: [{ required: true, message: `${this.$t('pleaseInput')}${this.$t('productName')}`, trigger: 'blur' }],
      //   processSpecificationNo: [{ required: true, message: `${this.$t('pleaseInput')}${this.$t('processSpecificationNumber')}`, trigger: 'blur' }],
      //   processFlow: [{ required: true, message: `${this.$t('pleaseInput')}${this.$t('processNo')}`, trigger: 'blur' }],
      //   packaingFormsCode: [{ required: true, message: `${this.$t('pleaseInput')}${this.$t('packageType')}`, trigger: 'change' }]
      // },
      tableData: [],
      errorIndex: null,
      tableColumns: [
        {
          prop: 'unit',
          label: 'Unit',
          templete: (_scope) => {
            return (
              <el-select
                v-model={_scope.row.unit}
                placeholder=''
                size={'small'}
                disabled={this.tableDisable}
              >
                <el-option label={'%'} value={'%'}></el-option>
                <el-option label={'Count'} value={'Count'}></el-option>
              </el-select>
            )
          }
        },
        {
          prop: 'highLimit',
          label: 'HighLimit',
          templete: (_scope) => {
            return (
              <el-input
                v-model={_scope.row.highLimit}
                disabled={this.tableDisable}
                size={'small'}
                onInput={(val) => {
                  _scope.row.highLimit = val.replace(/[^\d.]/g, '')
                }}
                clearable
              ></el-input>
            )
          }
        },
        {
          prop: 'logicH',
          label: 'Logic_H',
          templete: (_scope) => {
            return (
              <el-select
                v-model={_scope.row.logicH}
                placeholder=''
                size={'small'}
                disabled={this.tableDisable}
              >
                <el-option label={'<'} value={'<'}></el-option>
                <el-option label={'<='} value={'<='}></el-option>
              </el-select>
            )
          }
        },
        {
          prop: 'lowLimit',
          label: 'LowLimit',
          templete: (_scope) => {
            return (
              <el-input
                v-model={_scope.row.lowLimit}
                size={'small'}
                disabled={this.tableDisable}
                onInput={(val) => {
                  _scope.row.lowLimit = val.replace(/[^\d.]/g, '')
                }}
                clearable
              ></el-input>
            )
          }
        },
        {
          prop: 'logicL',
          label: 'Logic-L',
          templete: (_scope) => {
            return (
              <el-select
                v-model={_scope.row.logicL}
                placeholder=''
                disabled={this.tableDisable}
                size={'small'}
              >
                <el-option label={'>'} value={'>'}></el-option>
                <el-option label={'>='} value={'>='}></el-option>
              </el-select>
            )
          }
        },
        {
          prop: 'binNo',
          label: 'BinNo',
          templete: (_scope) => {
            return (
              <el-input
                size={'small'}
                v-model={_scope.row.binNo}
                disabled={this.tableDisable}
                clearable
              ></el-input>
            )
          }
        },
        {
          prop: 'binType',
          label: 'BinType',
          templete: (_scope) => {
            return (
              <el-select
                v-model={_scope.row.binType}
                placeholder=''
                size={'small'}
                disabled={this.tableDisable}
              >
                <el-option label={'HardBin'} value={'HardBin'}></el-option>
                <el-option label={'SoftBin'} value={'SoftBin'}></el-option>
                <el-option label={'Yield'} value={'Yield'}></el-option>
              </el-select>
            )
          }
        },
        {
          prop: 'binItem',
          label: 'BinName',
          templete: (_scope) => {
            return (
              <el-input
                size={'small'}
                v-model={_scope.row.binItem}
                disabled={this.tableDisable}
                clearable
              ></el-input>
            )
          }
        },
        {
          prop: '',
          label: this.$t('action'),
          width: '60px',
          templete: (_scope) => {
            return (
              <el-link
                type='primary'
                underline={false}
                disabled={this.tableDisable}
                on-click={() => this.scopedDelete(_scope)}
              >
                {this.$t('delete')}
              </el-link>
            )
          }
        }
      ]
    }
  },
  methods: {
    async handleOpen(row, isEdit = false) {
      if (row && row.id) {
        if (isEdit) {
          this.title = this.$t('details')
          this.tableDisable = isEdit
        } else {
          this.title = this.$t('modify')
        }
        this.formDisable = true
        const res = await getInfos({ id: row.id })
        this.infoForm = Object.assign({}, row)
        this.tableData = res.data
      } else {
        this.title = this.$t('add')
      }
      this.dialogVisible = true
      this.getPackageTypes()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    doSave() {
      // this.$refs['dataForm'].$refs['dynForm'].validate((valid) => {
      //   if (valid) {
      if (this.validFactor()) {
        if (this.infoForm.id) {
          doUpdate(this.$clearNull({ ...this.infoForm, subInfoList: this.tableData })).then(
            (res) => {
              this.$betterTips(res, this.handleClose, this.handleUpdate)
            }
          )
        } else {
          doAdd(this.$clearNull({ ...this.infoForm, subInfoList: this.tableData })).then(
            (res) => {
              this.$betterTips(res, this.handleClose, this.handleUpdate)
            }
          )
        }
      } else {
        // 这里的if防止下标为0时
        if (this.errorIndex) {
          this.$notify({
            message: `第${this.errorIndex}行: HighLimit不能小于LowLimit`,
            type: 'warning'
          })
        }
      }
      //   }
      // })
    },
    addpackageTypeList(value) {
      const find = this.packaingCodeList.map(c => c.id).some(v => v === value)
      if (!find) {
        this.packaingCodeList.unshift({ id: value, name: value })
      }
    },
    validFactor() {
      const bool = this.tableData.every(c => c.binNo &&
            Number(c.highLimit || 0) > Number(c.lowLimit || 0) &&
            (c.highLimit || c.lowLimit))
      const index = this.tableData.findIndex(c => Number(c.highLimit || 0) < Number(c.lowLimit || 0))
      this.errorIndex = index < 0 ? 0 : index + 1
      return bool
    },
    handleClose() {
      Object.assign(this.$data, this.$options.data.call(this))
    },
    handleUpdate() {
      this.$emit('initList')
    },
    handleAddCol() {
      this.tableData.push({})
    },
    scopedDelete(row) {
      this.tableData.splice(row.$index, 1)
    },
    async getPackageTypes() {
      const res = await getPackageTypeList()
      // this.$set(this.selectList, 'packaingFormsCode', res.data)
      this.packaingCodeList = res.data
    }
  }
}
</script>
<style lang="scss" scoped>
.opt-btns {
  display: flex;
  justify-content: flex-end;
  align-content: center;
  height: 40px;
  margin-bottom: 20px;
}
.table-box{
  width: 100%;
  max-height: 400px;
  overflow-y: auto;
}
.result-item {
  display: flex;
  .result-pass {
    margin-right: 20px;
  }
}
</style>
